package com.lanwf.admin.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.lanwf.common.model.SysAdmin;
import com.lanwf.common.model.SysSession;
import com.lanwf.admin.utils.Cons;


/**
 * @Auther: Lanwf
 * @Date: 2021/12/23 17:57
 * @Description:
 */
public class  AdminLoginInterceptor implements Interceptor {

    @Override
    public void intercept(Invocation inv) {


        Controller c = inv.getController();
        String cookie = c.getCookie(Cons.ADMIN_COOKIE);
        
        SysSession first = SysSession.dao.findFirst("select * from sys_session where id = ? ", cookie);

        if (StrKit.isBlank(cookie) || first == null ) {

            if(isAjaxRequest(c)){
                c.renderJson(Ret.fail("msg","登录超时,请重新登录"));
            }else{
                //未登录状态跳转到登录界面
                c.redirect("/admin/login");
            }

            return;
        }

        SysAdmin account = SysAdmin.dao.findById(first.getAccountId());
        if(account == null){
            if(isAjaxRequest(c)){
                c.renderJson(Ret.fail("msg","登录超时,请重新登录"));
            }else{
                //未登录状态跳转到登录界面
                c.redirect("/admin/login");
            }
            return;
        }


        if(StrKit.isBlank(account.getAvatar())){
            account.setAvatar(Cons.prj+"/assets/static/img/profile.jpg");
        }else{
            account.setAvatar(Cons.prj+account.getAvatar());
        }
        c.set("account",account.set("password",""));

        inv.invoke();
    }

    public boolean isAjaxRequest(Controller c) {
        return "XMLHttpRequest".equalsIgnoreCase(c.getHeader("X-Requested-With"));
    }
}
